<template>
	<view class="apply-container" v-if="Object.keys(info) != false">
		<block-view>
			<view class="title-wrapper">
				<view class="title">{{ info.title }}</view>
			</view>
			
			<view class="info-part" style="margin-bottom: 0;">
				<view class="info-list-item location-wrapper">
					<view class="title">活动地点:</view>
					<view class="note">{{ info.address || '不限' }}</view>
				</view>
				<view class="info-list-item">
					<view class="title">报名日期:</view>
					<view class="note">{{ activityDateFormat(info.enroll_date_start, info.enroll_date_end) }}</view>
				</view>
				<view class="info-list-item">
					<view class="title">活动日期:</view>
					<view class="note">{{ activityDateFormat(info.activity_date_start,info.activity_date_end) }}</view>
				</view>
				<view class="info-list-item">
					<view class="title">活动类型:</view>
					<view class="note">{{ typeFormat(info.type) }}</view>
				</view>
			</view>
			<view class="info-part pet-type">
				<view class="pet-item" v-if="info.pet_type == 1" :class="{'pet-item-active' : info.pet_type == 1}">猫猫</view>
				<view class="pet-item" v-if="info.pet_type == 2" :class="{'pet-item-active' : info.pet_type == 2}">狗狗</view>
				<view class="pet-item" v-if="info.pet_type == 3" :class="{'pet-item-active' : info.pet_type == 3}">不限</view>
			</view>
		</block-view>
		<block-view v-if="info.price_level">
			<view class="u-title">活动费用</view>
			<view class="cost-wrapper">
				<view class="cost-item" v-for="(cost, index) in activityCost" :key="index" 
					:class="{'cost-active': cost.active }" @click="chooseCost(index)" v-if="activityCost.length!==0" >
					<view class="top-part">
						<view class="title">{{ cost.name }}</view>
						<view class="price">¥{{ cost.price }}</view>
					</view>
					<view class="bottom-part" v-if="cost.active" @click.stop="() => {}">
						<uni-number-box :min="0" :max="info.remaining_num" :width="20" v-model="cost.num" @change="priceNumChange($event, index)"></uni-number-box>
					</view>
				</view>
			</view>
			<!-- <view class="tips">该主办方已经通过认证审核，请放心报名</view> -->
		</block-view>
		<block-view >
			<u-list-item title="See Wow福利券" title-weight="500" :show-arrow="true" :show-border="false"  
			:disabled="info.reward_num ==0 ? true : false" 
			:note="formatNote()"
			:note-color="info.reward_num==0?'#7B7B7B':'#00CAC0 '"
			:note-size="'13px'"
			 @click="selectReward"
			></u-list-item>
			<view class='f-show' v-if="Object.keys(reward).length > 0">
				<view class="f-discount">共优惠：¥{{discount_price}}</view><view class="f-total">合计：¥{{total_price}}</view>
			</view>
			
		</block-view>
	</view>
	
	<fixed-footer>
		<primary-btn :title="info?.like_member ? '下一步' : '提交报名'" @btnClick="next"></primary-btn>
	</fixed-footer>
</template>

<script>
	import { wxPay } from '../../network/pay'
	import { useUserStore } from '../../store/userStore'
	export default {
		data() {
			return {
				activityId: 0,
				info: {},
				total_num: 0,
				total_price: 0,
				discount_price: 0,
				activityCost: [],
				reward: {},
				userStore: useUserStore()
			}
		},
		onLoad(options) {
			this.activityId = options.activityId
			const eventChannel = this.getOpenerEventChannel();
			if(Object.keys(eventChannel).length > 0) {
				eventChannel.on('applyInfo', (data) => {
					this.info = data.info
				})
			}
			 uni.$on('selectInfo', (data) => {
				this.info = data.info;
				this.total_num = data.total_num;
				this.activityCost = data.activityCost;
				this.total_num = data.total_num;
				this.reward = data.reward
				this.calPrice();
			})
			
		},
		watch: {
			'info.price_level': {
				handler(val) {
					if (val) {
						if(Object.keys(this.activityCost).length == 0) {
							const list = JSON.parse(val)
							this.activityCost = list.map((item, index) => {
								return {
									...item,
									num: 1,
									active: index > 0 ? false : true
								}
							})
							this.calPrice();
						}
					}
				}
			}
		},
		methods: {
			calPrice() {
				if(Object.keys(this.activityCost).length > 0) {
					var total_price = 0;
					var i;
					var priceMin = 0;
					for ( i = 0; i< this.activityCost.length; i++) {
						var  item = this.activityCost[i]
						if (item.active) {
							var price = Number(item.price);
							total_price += price * item.num;
							if ((priceMin > 0 && price < priceMin) || priceMin == 0) {
								priceMin = price;
							}
						}
					}
					if(Object.keys(this.reward).length > 0) {
						if(this.reward.type == 1) {
							this.discount_price = total_price < this.reward.amount ? total_price : this.reward.amount;
							this.discount_price = this.changeNumber(this.discount_price);
							total_price =  total_price < this.reward.amount ? 0 : (total_price - this.reward.amount)
						}else{
							//this.discount_price  =  (total_price * (100 - this.reward.discount))/100
							//this.discount_price = this.discount_price.toFixed(2);
							//total_price = (total_price * this.reward.discount)/100;
							this.discount_price  =  (priceMin * (100 - this.reward.discount))/100;
							this.discount_price  = this.changeNumber(this.discount_price);
							total_price          = total_price - this.discount_price;
						}
					}
					
					this.total_price =  this.changeNumber(total_price);
				}
			},
			changeNumber (num){
				return Math.round(num * 100) / 100;
			},
			formatNote(){
				if(Object.keys(this.reward).length > 0) {
					return this.reward.title
				}else{
					return this.info.reward_num==0 ? '暂无福利券': this.info.reward_num+'张可用'
				}
			},
			//跳转到优惠券页面
			selectReward(){
				uni.navigateTo({
					url: '/pages/detail/selectReward?activityId='+ this.info.id,
					success: (res) => {
						res.eventChannel.emit('applyInfo', {
							info: this.info,
							total_num: this.total_num,
							activityCost: this.activityCost,
							total_price: this.total_price,
							reward:this.reward,
						})
					}
				})
			},
			// 下一步，如果设置了偏好收集就下一步，如果没有设置就直接提交报名
			async next() {
				let costList = []
				var link_url = '/pages/detail/index?activityId='+ this.activityId+"&isCheckCode=true&applySuccess=true";
				var link_url_error = '/pages/detail/index?activityId='+ this.activityId;
				if (this.activityCost.length != 0) {
					for await (let item of this.activityCost) {
						if (item.active) {
							costList.push({
								id: item.id,
								num: item.num
							})
						}
					}
					if (costList.length == 0) {
						uni.showToast({
							title: '请选择需要的套餐',
							icon: 'none'
						})
						return
					}
				}
				this.calculateTotalNum();
				if (this.info.remaining_num < this.total_num) {
					uni.showToast({
						title: '购买参与数不能超过'+ this.info.remaining_num  + "次",
						icon: 'none'
					})
					return ;
				}

				if (this.info.like_member) {
					uni.navigateTo({
						url: '/pages/detail/submitReg?activityId='+ this.activityId,
						success: (res) => {
							res.eventChannel.emit('preferenceInfo', {
								price_level: costList,
								reward: this.reward,
								preference: this.info.like_member
							})
						}
					})
				} else {
					const res = await this.$request.post('/api/activity/enroll', {
						activity_id: this.activityId,
						price_level: costList,
						like_member: '',
						reward_no: Object.keys(this.reward).length > 0 ? this.reward.reward_no : "",
					})
					if (res.code == 200) {
						if (!res.data) {
							uni.showToast({
								title: '报名成功',
								icon: 'success'
							})
							uni.$emit('applySuccess')
							setTimeout(() => {
								//isCheckCode
								uni.navigateTo({
									url: link_url
								})
								// uni.navigateBack({
								// 	delta: this.delta_num
								// })
							}, 1500)
							return
						}
						const { order_no , pay_price} = res.data
						if (pay_price > 0) {
							const data = {
								pay_type: 1,
								order_no,
								client: 1,
								openid: this.userStore.openid
							}
							wxPay('/api/pay/pay', data).then((payRes) => {
								uni.showToast({
									title: '报名成功',
									icon: 'success'
								})
								uni.$emit('applySuccess')
								setTimeout(() => {
									uni.navigateTo({
										url: link_url
									})
									// uni.navigateBack({
									// 	delta: this.delta_num
									// })
								}, 1500);
							}).catch((error) => {
								uni.showToast({
									title: '支付失败，可在订单管理继续完成支付',
									icon: 'none'
								})
								setTimeout(() => {
									uni.navigateTo({
										url: link_url_error
									})
									// uni.navigateBack({
									// 	delta: this.delta_num
									// })
								}, 1500);
							})
						}else{
							uni.showToast({
								title: '报名成功',
								icon: 'success'
							})
							uni.$emit('applySuccess')
							setTimeout(() => {
								uni.navigateTo({
									url: link_url
								})
								// uni.navigateBack({
								// 	delta: this.delta_num
								// })
							}, 1500);
						}

					}
				}
			},
			// 选择费用
			chooseCost(index) {
                this.calculateTotalNum();
				if (!this.activityCost[index].active && this.total_num < this.info.remaining_num) {
				    this.activityCost[index].num = 1
				}
				this.activityCost[index].active = this.activityCost[index].active == true ? false : true;
				this.calPrice();

			},
			calculateTotalNum()
			{
				this.total_num = 0;
				for (var i =0; i < this.activityCost.length; i++) {
					if (this.activityCost[i].active) {
						this.total_num += this.activityCost[i].num
					}
				}
			},			
			priceNumChange(value, index) {
				if (value == 0) {
					setTimeout(() => {
						this.activityCost[index].active = false;
						this.calPrice();
					}, 300)
				}else{
					//计算一下总的数量
					this.calculateTotalNum();
					this.calPrice();
					if (this.total_num > this.info.remaining_num) {
						uni.showToast({
							title: '购买参与数不能超过'+ this.info.remaining_num  + "次",
							icon: 'none'
						})
						setTimeout(() => {
							this.activityCost[index].num = this.activityCost[index].num -1
							this.calPrice();
							//this.activityCost[index].active = false
						}, 300)
					}
				}
				
			},
			activityDateFormat(startDate, endDate) {
				if (!startDate) {
					return '不限'
				}
				const s = startDate?.substring(0, startDate?.lastIndexOf(':')).replace(/\-/g, '.'),
					e = endDate?.substring(0, endDate?.lastIndexOf(':')).replace(/\-/g, '.')
				return `${s}～${e}`
			},
			typeFormat(type) {
				switch (type){
					case 1:
						return '宠物活动'
						break;
					case 2:
					return '宠物友好'
						break;
					case 3:
						return '宠物市集'
						break;
					case 4:
						return '其他活动'
						break;
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.apply-container {
		padding: 24rpx 30rpx;
		padding-bottom: 200rpx;
		
		.title-wrapper {
			display: flex;			
			align-items: center;
			margin-bottom: 30rpx;
			width: 100%;
			.title {
				font-size: 36rpx;
				font-weight: bold;
			}
		}
		.desc-content {
			font-size: 30rpx;
			padding: 30rpx 0;
		}
		.info-part {
			margin-bottom: 30rpx;
		}
		.pet-type {
			display: flex;
			align-items: center;
			margin-bottom: 5px;
			.pet-item {
				width: 150rpx;
				height: 64rpx;
				border-radius: 8px;
				text-align: center;
				line-height: 64rpx;
				font-size: 28rpx;
				background-color: #f6f6f6;
				margin-right: 20rpx;
			}
			.pet-item-active {
				background-color: #EBFBFA;
				border: 0.5px solid $uni-color-primary;
			}
		}
		
		.info-list-item {
			display: flex;
			align-items: center;
			padding: 24rpx 0;
			border-bottom: 1px solid #f0f0f0;
			.title {
				font-size: 30rpx;
				font-weight: 500;
				min-width: 130rpx;
			}
			.note {
				color: #666;
				padding-left: 16rpx;
				width: calc(100% - 130rpx);
				font-size: 28rpx;
			}
			&:last-child {
				border-bottom: none;
			}
		}
		.location-wrapper {
			display: flex;
			align-items: flex-start;
		}
		
		.tips {
			font-size: 28rpx;
			color: $uni-color-primary;
			text-align: center;
			padding-bottom: 5px;
		}
		.u-title {
			font-weight: 500;
		}
		.cost-wrapper {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			margin: 24rpx 0 4rpx;
			.cost-item {
				margin-right: 10rpx;
				background-color: #f6f6f6;
				border-radius: 8px;
				border: 0.5px solid #f6f6f6;
				width: 200rpx;				
				height: 216rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				padding: 20rpx 12px 10px 20rpx;
				margin-bottom: 20rpx;
				&:nth-of-type(3n) {
					margin-right: 0;
				}
				.top-part {
					font-size: 28rpx;
					.title {
						font-weight: 500;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						line-clamp: 2;
						-webkit-line-clamp: 2;
						overflow: hidden;
						text-overflow: ellipsis;
					}
					.price {
						margin-top: 6rpx;
						font-size: 34rpx;
					}
				}
				.bottom-part {
					display: flex;
					justify-content: flex-end;
				}
			}
			.cost-active {
				background-color: #EBFBFA;
				border: 0.5px solid $uni-color-primary;
			}
		}
		
	}
	:deep(.uni-numbox__value) {
		background-color: #fff !important;
		border-radius: 12rpx;
		border: 1px solid $uni-color-primary;
		width: 24px;
		height: 24px;
	}
	:deep(.uni-numbox-btns) {
		background: transparent !important;
	}
	.f-show{
		width: auto;
		//margin-left: 284rpx;
		text-align: right;
		.f-total{
			margin-left: 30rpx;
			display: inline;
			width: auto;
			height: 40rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #262626;
			line-height: 38rpx;
			text-align: left;
			font-style: normal;
			text-transform: none;
		}
		.f-discount{
			display: inline;
			width: auto;
			height: 32rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 26rpx;
			color: #7B7B7B;
			line-height: 30rpx;
			text-align: left;
			font-style: normal;
			text-transform: none;
		}
	}

</style>